﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using mesoBoard.Data;
using mesoBoard.Data.Repositories;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Collections;
using System.IO;

namespace mesoBoard.Services
{
    public static class Misc
    {
        public static Theme GetCurrentTheme()
        {
            ThemeRepository ThemeRep = new ThemeRepository(new mbEntities());

            Theme CurrentTheme;

            bool isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;

            if (SiteConfig.OverrideUserTheme.ToBool() || !isAuthenticated)  
                return CurrentTheme = ThemeRep.GetTheme(int.Parse(SiteConfig.BoardTheme.Value));
            else
                return CurrentTheme = ThemeRep.GetUserTheme(int.Parse(HttpContext.Current.User.Identity.Name));            
        }

        public static void ParseBBCodeScriptFile()
        {
            Theme CurrentTheme = GetCurrentTheme();
            string validHighlighters = SiteConfig.SyntaxHighlighting.Value;
            string[] highlighters = validHighlighters.ToLower().Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
            string[] options = SiteConfig.SyntaxHighlighting.Options.ToLower().Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
            string[] tohide = options.Except(highlighters).ToArray();
            
            string originalFile;

            using (StreamReader file = new StreamReader(HttpContext.Current.Server.MapPath("~/Themes/" + CurrentTheme.FolderName + "/Content/Scripts/bbcode-set.js")))
            {
                originalFile = file.ReadToEnd();
            }

            string[] splitText = originalFile.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            List<string> found = new List<string>();

            foreach (string h in tohide)
            {
                found.AddRange(splitText.Where(x => x.Contains(h)).ToList());
            }

            found = found.Distinct().ToList();

            foreach (string s in found)
            {
                originalFile = originalFile.Replace(s, "// " + s);
            }

            using (StreamWriter writeit = File.CreateText(HttpContext.Current.Server.MapPath("~/Themes/" + CurrentTheme.FolderName + "/Content/Scripts/bbcode-set-parsed.js")))
            {
                writeit.Write(originalFile);
            }
        }
      
    }
}
